package mybatis;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Config;
import tk.mybatis.mapper.mapperhelper.MapperHelper;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisDemo {

    private static final Logger log = LoggerFactory.getLogger(MyBatisDemo.class);

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        log.info("开始执行！！！！！！！！！！！！！！！！！！！");
        selectOne();
    }

    private static void selectList(){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            PageHelper.startPage(1,2);
            Page<User> users = mapper.selectList();

            log.info("第几页：{}", users.getPageNum());
            log.info("每页数量：{}", users.getPageSize());
            log.info("总页数：{}", users.getPages());
            log.info("总记录数：{}", users.getTotal());

            for (User user : users) {
                log.info("查询结果： {}", user);
            }
        }
    }



    private static void selectOne(){
        try (SqlSession session = openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            User u = mapper.selectOne(new User(1));
            log.info("查询结果：{}",u);
        }
    }


    private static SqlSession openSession(){
        //事务自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        MapperHelper mapperHelper = new MapperHelper();
        Config config = new Config();
        //主键自增回写方法,默认值MYSQL
        config.setIDENTITY("SQLITE");
        //支持getter和setter方法上的注解
        config.setEnableMethodAnnotation(true);
        //设置 insert 和 update 中，是否判断字符串类型!=''
        config.setNotEmpty(true);
        //校验Example中的类型和最终调用时Mapper的泛型是否一致
        config.setCheckExampleEntityClass(true);
        //启用简单类型
        config.setUseSimpleType(true);
        //枚举按简单类型处理
        config.setEnumAsSimpleType(true);
        //自动处理关键字 - mysql
        config.setWrapKeyword("`{0}`");
        //设置配置
        mapperHelper.setConfig(config);
        // 注册自己项目中使用的通用Mapper接口，这里没有默认值，必须手动注册
        mapperHelper.registerMapper(Mapper.class);
        //配置完成后，执行下面的操作
        mapperHelper.processConfiguration(sqlSession.getConfiguration());
        return sqlSession;
    }
}
